package com.fingerchar.api.service;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fingerchar.core.base.service.impl.BaseService;
import com.fingerchar.db.dao.FcUsdtRechargeMapper;
import com.fingerchar.db.dao.ext.FcUserExtMapper;
import com.fingerchar.db.domain.FcUser;
import com.fingerchar.db.domain.TtCalRecord;
import com.fingerchar.db.dto.CalSumDto;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author tangzf
 * @date 2022/9/10
 */
@Service
public class TtCalRecordService {

    @Resource
    private BaseService baseService;
    @Resource
    FcUserExtMapper fcUserExtMapper;

    public List<CalSumDto> sumCalByCreateTime(boolean isGroup) {

        Date now = DateUtil.parse(DateUtil.format(new Date(), "yyyy-DD-dd"));
        Date yesterday = DateUtil.parse(DateUtil.format(DateUtils.addDays(new Date(), -1), "yyyy-DD-dd"));
        QueryWrapper<TtCalRecord> wrapper = new QueryWrapper<>();
        //大于等于昨天
        wrapper.ge("create_time", yesterday.getTime())
                //小于今天
                .lt("create_time", now.getTime());
//        if (isGroup) {
//            wrapper.groupBy("address");
//        }
        List<TtCalRecord> ttCalRecords = baseService.findByCondition(TtCalRecord.class, wrapper);
        if(!isGroup){
            BigInteger sumAmount = ttCalRecords.stream().map(TtCalRecord::getAmount).reduce(BigInteger.ZERO, BigInteger::add);
            CalSumDto calSumDto = new CalSumDto();
            calSumDto.setAmount(sumAmount);
            return Lists.newArrayList(calSumDto);
        }else {
            List<CalSumDto> calSumDtos = new ArrayList<>();
            Map<String, List<TtCalRecord>> stringListMap = ttCalRecords.stream().collect(Collectors.groupingBy(TtCalRecord::getUserAddress));
            for (String key : stringListMap.keySet()) {
                CalSumDto calSumDto = new CalSumDto();
                calSumDto.setUserAddress(key);
                BigInteger sumAmount = stringListMap.get(key).stream().map(TtCalRecord::getAmount).reduce(BigInteger.ZERO, BigInteger::add);
                calSumDto.setAmount(sumAmount);
                calSumDtos.add(calSumDto);
            }
            return calSumDtos;
        }



    }

    public int insert(TtCalRecord ttCalRecord){
        return baseService.save(ttCalRecord);
    }

}
